import axios from "axios";
import { ElLoading, ElMessage } from 'element-plus'
import { useDemoStore } from '../pinia/index'

const store = useDemoStore()

let isDev = process.env.NODE_ENV === "development";

let baseURL;
if (isDev) {
  baseURL = 'http://192.168.2.254';
  //baseURL = 'http://test1.files99.com/';
  window.localStorage.setItem('url',baseURL);
} else {
  baseURL = "http://192.168.2.254";
  //baseURL = 'http://test1.files99.com/';
  window.localStorage.setItem('url',baseURL);
}

const service = axios.create({
  headers: { 'Content-Type': 'multipart/form-data' },
  baseURL,
  timeout: 30000, // 请求超时时间(因为需要调试后台,所以设置得比较大)
});

let loadObj;
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (!loadObj) {
      loadObj = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
    }
     // 请求头添加token
    config.headers['token'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE2NzQ5NTk1MDcsIm5iZiI6MTY3NDk1OTYwNywiZXhwIjoxNjc3NTUxNTA3LCJpZCI6NDAwMDY5fQ.yFRYHJt60gjMIF5V18zH_TDpMMjHZn3Js_762ot4wvE';
    return config;
  },
  (error) => {
    setTimeout(() => {
      loadObj.close();
    }, 300);
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    setTimeout(() => {
      loadObj.close();
    }, 300);
    const res = response.data;

    if (res.Status == 0) {
      return res;
    } else {
      ElMessage(res.Message);
      return res;
    }
  },
  (error) => {
    setTimeout(() => {
      loadObj.close();
    }, 300);
    ElMessage(error.message);
    return Promise.reject(error.message);
  }
); 
export default service;